package com.sajus.billing.client.util;

import java.io.InputStream;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class EJBRemoteServiceLocator implements EJBServiceLocator {
	private static final String POS_REMOTE_CLIENT_PROPERTIES = "pos-remote-client.properties";
	static private EJBServiceLocator instance = new EJBRemoteServiceLocator();

	private EJBRemoteServiceLocator() {
		super();
	}

	public static EJBServiceLocator getInstance() {
		return instance;
	}

	public <T> T locate(EJBs ejb) throws NamingException {
        Properties p = new Properties();
        try {
        	InputStream stream = this.getClass().getClassLoader().getResourceAsStream(POS_REMOTE_CLIENT_PROPERTIES);
        	if (stream == null) {
        		System.out.println("Null stream");
        	}
            p.load( stream );
            stream.close();
        } catch (Throwable t) {
        	t.printStackTrace();
        	new RuntimeException("Cannot load the properties for the remote client. Make sure you have pos-remote-client.properties in the classpath.");
        }

        p.put("java.naming.factory.initial","org.jboss.naming.remote.client.InitialContextFactory");
        p.put("java.naming.factory.url.pkgs","org.jboss.ejb.client.naming");
        // instead of this use jboss-ejb-client.properties in client classpath
        //   p.put("jboss.naming.client.ejb.context", true);
        p.put(Context.SECURITY_PRINCIPAL, "posapp");
        p.put(Context.SECURITY_CREDENTIALS, "apppos");
        InitialContext ctx = new InitialContext(p);
        Object o = ctx.lookup("ejb:WebPOSEAR/WebPOSEJB/" + ejb.toString() + "!" + ejb.getRemoteInterface() );
        ctx.close();
        return (T)o;
	}
}
